import { constantRoutes } from "@/router";
import Layout from "@/views/layout/index.vue"
import { Module } from 'vuex'
import { RouteRecordRaw } from 'vue-router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles: string[], route: any) {
    if (route.meta && route.meta?.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }
}

const SET_MENU = 'SET_MENU'
const SET_ROUTE = 'SET_ROUTE'
interface PermissionState {
    addRoutes?: RouteRecordRaw[];
    routes?: RouteRecordRaw[];
    menus?: RouteRecordRaw[];
}
// 菜单过滤
function filterSyncMenu(routes: RouteRecordRaw[], roles: string[], root = false) {
    for (let i = 0; i < routes.length; i++) {
        let route = routes[i]
        if (root && route.children?.length === 1) {
            const child: any = route.children[0]
            if (child.meta && child.meta.isRoot) {
                if (!child.path.startsWith("/")) {
                    child.path = route.path + '/' + child.path
                }
                routes[i] = child
            }
        }
        if (route.children) {
            filterSyncMenu(route.children, roles)
        }
    }
}
// 路由过滤
function filterSyncRoutes(routes: RouteRecordRaw[], roles: string[]) {
    const res: any = []
    routes.forEach(route => {
        const tmp = { ...route }
        if (hasPermission(roles, tmp)) {
            if ((route.component as any) == 'layout') {
                route.component = Layout
            }
            if (route.children) {
                tmp.children = filterSyncRoutes(route.children, roles)
            }
            res.push(tmp)
        }
    })
    return res
}
const permission: Module<PermissionState, any> = {
    state: {
        addRoutes: [],
        routes: [],
        menus: []
    },
    mutations: {
        [SET_MENU](state, menus: []) {
            state.menus = menus
        },
        [SET_ROUTE](state, routes: []) {
            state.addRoutes = routes
            state.routes = constantRoutes.concat(routes)
        }
    },
    actions: {
        GenerateRoutes: function ({ commit }, roles: string[]) {
            return new Promise<RouteRecordRaw[]>((resolve) => {
                // 创建路由表
                let accessedRoutes = []
                // 如果是管理员，则包含全部路由
                if (roles.includes('admin')) {
                    accessedRoutes = constantRoutes.concat([])
                } else {
                    accessedRoutes = filterSyncRoutes(constantRoutes, roles)
                }
                // 根据路由表构建菜单
                let menus = JSON.parse(JSON.stringify(accessedRoutes))
                // console.log("====menus======")
                // console.log(menus)
                // console.log("====menus======")
                filterSyncMenu(accessedRoutes, roles, true)
                console.log(accessedRoutes)
                commit(SET_ROUTE, accessedRoutes)
                commit(SET_MENU, menus)
                resolve([])
            })
        }
        // GenerateRoutes: function ({ commit }, roles: string[]) {
        //     return new Promise<RouteRecordRaw[]>((resolve) => {
        //         // 复制路由表
        //         let menus = JSON.parse(JSON.stringify(constantRoutes.concat([])));
        //         // 过滤菜单
        //         filterSyncMenu(menus, roles, true)
        //         // 生成路由空表
        //         const routes = JSON.parse(JSON.stringify([]))
        //         // 过滤路由表
        //         filterSyncRoutes(routes)
        //         commit(SET_ROUTE, routes)
        //         commit(SET_MENU, menus)
        //         resolve([])
        //     })
        // }
    }
}
export default permission
